package dxn.nl.file.client.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@ConditionalOnProperty(name="cms.export.client.enable", havingValue="true")
public class ExportClientDealBoot implements CommandLineRunner, DisposableBean, ApplicationListener<ContextClosedEvent> {
    private static final Logger log = LoggerFactory.getLogger(ExportClientDealBoot.class);
    //创建成员变量以便方法获取
    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${cms.export.server.host}")
    private String serverHost;

    public static ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);

    public void run(String... args) throws Exception {
        try {
            log.info("启动导出处理客户端任务---------");
            if(serverHost == null || serverHost=="")
            {
                // 通知应用程序退出
                System.exit(-1);
            }

            String[] hosts = serverHost.split(",");

            for(String host:hosts)
            {
                String[] ipPort = host.split(":");
                if(ipPort.length != 2)
                {
                    log.error(host+"服务地址不正确---------");
                    System.exit(-1);
                }
                int port = Integer.parseInt(ipPort[1]);
                ExportClientDealServer dealServer = new ExportClientDealServer(applicationName,ipPort[0],port);
                dealServer.init();
                ExportClientSocketManager.dealServerList.add(dealServer);
            }

            Boolean connectResult = ExportClientSocketManager.checkAndConnect();
            if(!connectResult)
            {
                log.error("服务链接失败---------");
                System.exit(-1);
            }

            log.debug("start...");
            // 在1s后执行任务 之后每2s执行一次任务
            pool.scheduleAtFixedRate(() -> {
                try {
                    for(ExportClientDealServer entry: ExportClientSocketManager.dealServerList)
                    {
                        entry.connect();
                    }
                } catch (Exception e) {
                    log.error("连接失败",e);
                }
            }, 5, 3, TimeUnit.SECONDS);
        }
        catch (Exception ex)
        {
            log.error("链接失败",ex);
            System.exit(-1);
        }
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        try {
            log.info("开始停止导出任务");
            endJob();
        }
        catch (Exception ex)
        {

        }
    }

    @Override
    public void destroy() throws Exception {
//        log.info("导出任务注销6-1");
//        endJob();
//        log.info("导出任务注销6-2");
    }

    private void endJob()
    {
        try {
            if(!pool.isShutdown())
            {
                pool.shutdownNow();
                log.info("导出任务检查连接状态job终止");
            }
        }
        catch (Exception ex)
        {
            log.error("导出任务注销",ex);
        }

        try {
            for(ExportClientDealServer entry: ExportClientSocketManager.dealServerList)
            {
                entry.destroy();
            }
        }
        catch (Exception ex)
        {
            log.error("导出任务注销异常",ex);
        }
    }
}
